#!/usr/bin/env python
#usage: monitor_form.py data/
import sys
from argparse import ArgumentParser
import numpy as np
import os

def traversal_folder(folder_path):
    if folder_path is None:
        print('folder_path is None!')
        sys.exit(0)
    filelist = []
    for root, dirs, files in os.walk(folder_path):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            filelist.append(file_path)
    return filelist

def format_monitor(monitor_file):
#    f = open(sys.argv[1],'r')
    f = open(monitor_file, 'r')
    lines = f.readlines()
    f.close()
    fname = monitor_file.split("/")[-1]
    f1name = monitor_file.replace(fname,"tmp.txt")
    f1 = open(f1name,'a')
    for i in range(len(lines)):
        if i%2 == 0:
            timetag = lines[i].split('\t')[0]
#            print(timetag)
            currents = lines[i].split('\t')[1]
            currents = currents.split(',')
            c = np.zeros(len(currents))
            for j in range(len(currents)):
                c[j] = float(currents[j])
            wline = timetag+' '+str(np.median(c))+'\n'
            f1.writelines(wline)
    f1.close()
    #os.system("mv tmp.txt " + sys.argv[1])
    os.system("mv " + monitor_file + ' ' + monitor_file+'.bak')
    os.system("mv " + f1name + ' ' + monitor_file)
    os.system("rm " + f1name)
    
def main(path=None, **kwargs):
    filelist = traversal_folder(path)
#    print('filelist: {}'.format(filelist))
    for f in filelist:
        if f[len(f)-18:] == 'monitor_sphere.txt':
            if f+'.bak' in filelist:
                print('{} has been formated, pass'.format(f))
            else:
                print('formating: {}'.format(f))
                format_monitor(f)
        elif f[len(f)-17:] == 'monitor_calib.txt':
            if f+'.bak' in filelist:
                print('{} has been formated, pass'.format(f))
            else:
                print('formating: {}'.format(f))
                format_monitor(f)            

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('path', type=str, help='file name or directory name')
    args = parser.parse_args()
    main(path=args.path)
    
